
'''
    工具类

'''

import base64
import json  # json相关
import os  # 文件流相关
import zipfile  # zip亚索文件
import shutil  # 删除整个文件夹


def fromFile(url):
    try:
        with open(url, 'r', encoding='utf-8') as fp:
            return fp.read()
    finally:
        fp.close()
        
def fromFile2Base64(url):
    try:
        with open(url, 'rb') as f1:
            return str(base64.b64encode(f1.read()), encoding='utf-8')
    finally:
        f1.close()

def writeInFile(toFile, content):
    try:
        with open(toFile, 'w', encoding='utf-8') as fp:
            fp.write(content)
    finally:
        fp.close()


def fromJsonAsDict(url):
    return json.loads((fromFile(url)))


def writeDictInFile(url, dict1):
    writeInFile(url, json.dumps(dict1, ensure_ascii=False, indent=2))

def revealInFileExplorer(targetDir):
    try:
        os.startfile(targetDir)
    except:
        os.system("explorer.exe %s" % targetDir)


def zipFile(src, dest):
    '''
        src: 目标文件位置   D:/123.txt
        dest: 压缩后输出的zip路径 D:/123.zip
    '''
    with zipfile.ZipFile(dest, 'w',zipfile.ZIP_DEFLATED) as p:
        
        p.write(src,os.path.split(src)[1])

        p.close()     


def zipFiles(src,dest):
    '''
        src: 目标文件夹位置   D:/hellowd
        dest: 压缩后输出的zip路径 D:/hellowd.zip
    '''
    with zipfile.ZipFile(dest, 'w',zipfile.ZIP_DEFLATED) as pZip:
        for folder, _, files in os.walk(src):
            relative_url = folder.replace(src, '')
            for file in files:
                pZip.write(os.path.join(folder,file),os.path.join(relative_url,file))
        pZip.close()

def removeFile(url):
    if os.path.isdir(url):
        shutil.rmtree(url)
    else:
        os.remove(url)



